package com.healthdata.service.impl;

import com.healthdata.entity.DataRow;
import com.healthdata.service.ExportService;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.data.domain.Page;
import org.springframework.http.*;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;

@Service
public class ExportServiceImpl implements ExportService {

    // 新增公共方法实现
    @Override
    public byte[] exportToExcel(List<DataRow> data) throws IOException {
        return exportToExcelInternal(data);
    }

    @Override
    public ResponseEntity<byte[]> exportData(String format, List<DataRow> data, String filename) {
        try {
            byte[] content;
            MediaType mediaType;

            switch (format.toUpperCase()) {
                case "CSV":
                    content = exportToCsv(data);
                    // 修正CSV的MediaType为text/csv
                    mediaType = MediaType.parseMediaType("text/csv");
                    break;
                case "EXCEL":
                    // 调用内部Excel导出方法
                    content = exportToExcelInternal(data);
                    mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    break;
                case "PDF":
                    content = exportToPdf(data);
                    mediaType = MediaType.APPLICATION_PDF;
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported format: " + format);
            }

            return buildResponse(content, mediaType, filename);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @Override
    public ResponseEntity<byte[]> exportPageData(String format, Page<DataRow> page, String filename) {
        return exportData(format, page.getContent(), filename);
    }

    @Override
    public ResponseEntity<byte[]> exportStatistics(String format, Map<String, Object> statistics, String filename) {
        try {
            byte[] content;
            MediaType mediaType;

            switch (format.toUpperCase()) {
                case "CSV":
                    content = exportStatsToCsv(statistics);
                    // 修正CSV的MediaType为text/csv
                    mediaType = MediaType.parseMediaType("text/csv");
                    break;
                case "JSON":
                    content = exportStatsToJson(statistics);
                    mediaType = MediaType.APPLICATION_JSON;
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported format for statistics: " + format);
            }

            return buildResponse(content, mediaType, filename);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @Override
    public ResponseEntity<byte[]> exportTableData(String format, List<DataRow> data, String filename) {
        return exportData(format, data, filename);
    }

    // 将原有的私有方法重命名，避免与接口方法冲突
    private byte[] exportToExcelInternal(List<DataRow> data) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("健康数据");

        // 创建表头行
        if (!data.isEmpty()) {
            DataRow firstRow = data.get(0);
            Row headerRow = sheet.createRow(0);

            int colIndex = 0;
            for (String header : firstRow.getValues().keySet()) {
                Cell cell = headerRow.createCell(colIndex++);
                cell.setCellValue(header);
            }

            // 填充数据
            for (int i = 0; i < data.size(); i++) {
                DataRow rowData = data.get(i);
                Row row = sheet.createRow(i + 1);

                colIndex = 0;
                for (Object value : rowData.getValues().values()) {
                    Cell cell = row.createCell(colIndex++);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    }
                }
            }

            // 自动调整列宽
            for (int i = 0; i < firstRow.getValues().size(); i++) {
                sheet.autoSizeColumn(i);
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        workbook.close();

        return out.toByteArray();
    }

    // 其他辅助方法保持不变...
    private byte[] exportStatsToCsv(Map<String, Object> statistics) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out);

        try (CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
            // 写入表头
            csvPrinter.printRecord("统计项", "值");

            // 写入统计数据
            for (Map.Entry<String, Object> entry : statistics.entrySet()) {
                csvPrinter.printRecord(entry.getKey(), entry.getValue());
            }
        }

        return out.toByteArray();
    }

    private byte[] exportStatsToJson(Map<String, Object> statistics) throws IOException {
        // 简单实现，实际项目中应使用JSON库
        StringBuilder jsonBuilder = new StringBuilder("{");
        boolean first = true;

        for (Map.Entry<String, Object> entry : statistics.entrySet()) {
            if (!first) {
                jsonBuilder.append(",");
            }
            jsonBuilder.append("\"").append(entry.getKey()).append("\":");

            Object value = entry.getValue();
            if (value instanceof String) {
                jsonBuilder.append("\"").append(value).append("\"");
            } else {
                jsonBuilder.append(value);
            }

            first = false;
        }

        jsonBuilder.append("}");

        return jsonBuilder.toString().getBytes();
    }

    private byte[] exportToCsv(List<DataRow> data) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out);

        try (CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
            // 写入表头（假设所有行具有相同的键）
            if (!data.isEmpty()) {
                DataRow firstRow = data.get(0);
                csvPrinter.printRecord(firstRow.getValues().keySet());

                // 写入数据
                for (DataRow row : data) {
                    csvPrinter.printRecord(row.getValues().values());
                }
            }
        }

        return out.toByteArray();
    }

    private byte[] exportToPdf(List<DataRow> data) throws DocumentException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        if (data.isEmpty()) {
            return new byte[0];
        }

        Document document = new Document();
        PdfWriter.getInstance(document, out);
        document.open();

        // 创建表格（列数由第一行决定）
        DataRow firstRow = data.get(0);
        PdfPTable table = new PdfPTable(firstRow.getValues().size());

        // 添加表头
        for (String header : firstRow.getValues().keySet()) {
            PdfPCell cell = new PdfPCell(new Phrase(header));
            cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
            table.addCell(cell);
        }

        // 添加数据
        for (DataRow row : data) {
            for (Object value : row.getValues().values()) {
                table.addCell(value != null ? value.toString() : "");
            }
        }

        document.add(table);
        document.close();

        return out.toByteArray();
    }

    private ResponseEntity<byte[]> buildResponse(byte[] content, MediaType mediaType, String filename) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(mediaType);

        // 修正Content-Disposition头，使用attachment而不是form-data
        headers.setContentDisposition(ContentDisposition
                .attachment()
                .filename(filename)
                .build());

        headers.setContentLength(content.length);

        // 添加通用的安全响应头
        headers.set("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
        headers.set("X-Content-Type-Options", "nosniff");
        headers.set("X-XSS-Protection", "0");
        headers.set("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
        headers.set("Pragma", "no-cache");
        headers.set("Expires", "0");
        headers.set("X-Frame-Options", "DENY");

        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }
}